package com.bms.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

/**
 * @author Lan
 */
public class Function {

	protected static Logger logger = Logger.getLogger(Function.class);

	/**
	 * 转码[GBK -> ISO-8859-1]
	 * @author Lan
	 * @param str
	 * @return
	 */
	public static String gbkToiso8859(String str) {
		String result = "";
		try {
			if(StringUtils.isNotBlank(str)){
				result = new String(str.getBytes("GBK"), "iso-8859-1");
			}
		} catch (UnsupportedEncodingException e) {
			logger.error("转码出错", e);
		}
		return result;
	}
	
	/**
	 * 获取当前操作系统的后缀
	 * 
	 * @author Lan
	 * @return linux/windows
	 */
	public static String getSystemSuffix() {
		String suffix = "";
		if (isLinuxOS()) {
			// 若为linux系统
			suffix = "linux";
		} else {
			// windows 系统
			suffix = "windows";
		}
		return suffix;
	}

	/**
	 * 判断当前的操作系统是否为Linux
	 * 
	 * @author Lan
	 * @return true-Linux,false-Windows
	 */
	public static boolean isLinuxOS() {
		boolean flag = false;
		String osName = System.getProperty("os.name");

		if (StringUtils.indexOf(osName, "Windows") != -1) {
			flag = false;
		} else {
			flag = true;
		}
		return flag;
	}
	
	/**
	 * 获取classes目录的绝对路径
	 * @return
	 */
	public static String getAbsolutePath(Class<?> inputClass) {
		String path = null;
		try {
			path = URLDecoder.decode(inputClass.getResource("/").getPath(),"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return path;
	}
	
	 /**
	 * @author Lan
	 * @param code 0-新文件目录,1-待审核目录,2-待发布目录, 33-统计日志目录, -1-接口数据文件获取后的（临时）保存目录
	 * @return 根据操作系统获取配置文件中的目录全路径，目录若不存在，则自动创建
	 */
	public static String getFileRootDir(int code){
		String suffix = getSystemSuffix();
		String dirPath = "";
		if(code == 0){
			dirPath = StringUtils.trim(PropUtil.getStrValue("newFilesDir_" + suffix));
		} else if (code == 1) {
			dirPath = StringUtils.trim(PropUtil.getStrValue("waitAuditDir"));
		} else if (code == 2) {
			dirPath = StringUtils.trim(PropUtil.getStrValue("waitPublishDir_" + suffix));
		} else if (code == 33){
			dirPath = StringUtils.trim(PropUtil.getStrValue("statis_sync_dir_" + suffix));
		} else if (code == -1){
			dirPath = StringUtils.trim(PropUtil.getStrValue("data.tempdir." + suffix));
		}
		
		if(StringUtils.isNotBlank(dirPath))
			FileUtil.createDir(dirPath);
		return dirPath;
	}
}
